package com.ydc.ln.commons.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;

import org.junit.Test;

/**
 * 文件(夹)操作工具类
 * @author ydc
 *
 */
public class FileUtil {
	
	@Test
	public void testCharSet() {
		Charset cs = Charset.defaultCharset();
		System.out.println(cs);
	}
	
	@Test
	public void testURL() {
		URL url = this.getClass().getResource("");
		System.out.println(url.toString());
	}
	
	@Test
	public void testReadFile02() throws Exception {
		BufferedReader br = new BufferedReader(new FileReader("f:\\www.csdn.net.sql"));
		int count = 0;
		while (br.ready() && count < 100) {
			String str = br.readLine();
			System.out.println("--" + count++ + "\t" + str);
			String[] propArray = str.split("#");
//			for (String sTmp : propArray) {
//				System.out.println(sTmp.trim());
//			}
			
		}
	}
	
	/**
	 * 读取某文件的内容
	 * @throws Exception
	 */
	@Test
	public void testReadFile01() throws Exception {
		URL url = this.getClass().getResource("/primes.txt");
		
		File file = new File(url.toURI());
		file = new File("f:\\www.csdn.net.sql");
		System.out.println(file.getAbsolutePath());
		FileInputStream fis = new FileInputStream(file);
		
		byte[] bytes = new byte[1024];
		StringBuffer strBuffer = new StringBuffer();
		int re = fis.read(bytes);
		System.out.println(re);
		while(-1 != re) {
			String str = new String(bytes, "GBK");
			strBuffer.append(str);
			re = fis.read(bytes);
			System.out.println("--" + str);
			System.gc();
			// System.out.println(re);
		}
		String strDest = strBuffer.toString();
		System.out.println(strDest);
		System.out.println(strDest.length());
	}	
	
	public static String readTxt(String filePath) {
		StringBuffer strBuff = new StringBuffer();
		return strBuff.toString();
	}
	
	public static void main(String[] args) {
		File src = new File("C:/Users/leo/Desktop/yidu");
		File dst = new File("C:/Users/leo/Desktop/dd/mm");
		copy(src, dst,true,true);//剪切
	}

	public static boolean rename(File file,String name){
		String str = file.getParent();
		if(!str.endsWith(File.separator))
			str += File.separator;
		return file.renameTo(new File(str+name));
	}

	public static void delete(File file){
		if(file.isFile()){
			file.delete();
		}else if(file.isDirectory()){
			File[] list = file.listFiles();
			for(int i=0;i<list.length;i++){
				delete(list[i]);				
			}
			file.delete();
		}
	}

	@Deprecated
	public static void cut(File src,File dst){
		copy(src, dst,true,false);
		delete(src);
	}
//上面的cut方法将文件夹全部复制后再删除整个文件夹，这种方法不好。因为如果有几个文件复制失败，源文件也会都被删除了
//若要剪切应该用下面的copy方法，将参数cut设为true,它是复制一个删除一个，复制失败就不会删除源文件

	/**
	 * 
	 * @param src：源文件（夹）
	 * @param dst：目标文件（夹）
	 * @param forced：如果遇到同名文件，是否覆盖
	 * @param cut：复制完是否删除源文件，若设为true，效果如同剪切
         * 注意：dst是目标路径而不是目标路径所在的文件夹，比如要不c:\dir复制到d:\盘下，则dst应该是File("d:\dir")而不是File("d:\")
	 */	
	public static void copy(File src,File dst,boolean forced,boolean cut){
		if(src.isFile()){
			if(!dst.isFile() || forced)
				try {
					dst.createNewFile();
					_copy(src, dst);
					if(cut)
						src.delete();
				} catch (IOException e) {
					e.printStackTrace();
				}			
		}
		else if(src.isDirectory()){
			dst.mkdirs();
			File[] list = src.listFiles();
			for(int i=0;i<list.length;i++){
				String rp = list[i].getAbsolutePath().substring(src.getAbsolutePath().length(), list[i].getAbsolutePath().length());
				File dstFile = new File(dst.getAbsolutePath()+rp);
				copy( list[i],dstFile,forced,cut);				
			}
			if(cut)
				src.delete();
		}
	}
	private static void _copy(File src,File dst) throws IOException{
		
		FileChannel dstfc = null;
		FileChannel srcfc = null;
		try {
			dstfc = new FileOutputStream(dst).getChannel();
			srcfc = new FileInputStream(src).getChannel();
			ByteBuffer buf = ByteBuffer.allocate(4*1024);
			while(srcfc.size()>srcfc.position()){
				buf.clear();
				srcfc.read(buf);
				buf.flip();
				dstfc.write(buf);
			}
		
		} finally {
			try {
				if(dstfc != null)
					dstfc.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				if(srcfc != null)
					srcfc.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	// copy start
	
}